//
//  AddressEditVC.m
//  KuWoCan
//
//  Created by hwd on 17/3/15.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "AddressEditVC.h"
#import "AddressEditCell.h"
#import "NWAddressRequest.h"

@interface AddressEditVC () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) AddressEditCell *addressEditCell;

@end

@implementation AddressEditVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUpUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setUpUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    if (_requestType == RequestTypeAddAddress)
    {
        self.title = @"添加地址";
    }
    else
    {
        self.title = @"修改地址";
    }
    
    [self createRightButton:@"保存" selector:@selector(saveAddressAction)];
    
    //创建列表
    _tableview = [[TPKeyboardAvoidingTableView
                   alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
    _tableview.backgroundColor = KwBgColor;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableview.estimatedRowHeight = 40.0;
    _tableview.rowHeight = UITableViewAutomaticDimension;
    _tableview.delegate = self;
    _tableview.dataSource = self;
    [self.view addSubview:_tableview];
    [_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.left.right.equalTo(@0);
        make.bottom.equalTo(@0);
    }];
}

- (BOOL)checkInfoWithInfoArr:(NSArray *)infoArr
{
    BOOL isOk = YES;
    for (NSString *str in infoArr)
    {
        if ([CommonTool checkStringIsEmpty:str] == YES)
        {
            isOk = NO;
        }
    }
    if ([self.addressEditCell.selectBtn.titleLabel.text isEqualToString:@"点击选择"]) {
        return NO;
    }
    return isOk;
}


//保存
- (void)saveAddressAction
{
    NSArray *infoArr = @[_addressEditCell.nameTf.text,_addressEditCell.teleTf.text,_addressEditCell.addressTf.text];
    if ([self checkInfoWithInfoArr:infoArr] == YES)
    {
        if (!isMobileNumber(infoArr[1])) {
            [SVProgressHUD showErrorWithStatus:@"请填写正确的手机号码"];
            return;
        }
        NWAddressRequest *request = [[NWAddressRequest alloc] init];
        if (_requestType == RequestTypeAddAddress)
        {
            [request startRequestAddAddressWithUserId:[Singleton shareInstance].userId name:_addressEditCell.nameTf.text phone:_addressEditCell.teleTf.text region:_addressEditCell.selectBtn.titleLabel.text address:_addressEditCell.addressTf.text];
        }
        else
        {
            [request startRequestChangeAddressWithAID:_model.id name:_addressEditCell.nameTf.text phone:_addressEditCell.teleTf.text region:_addressEditCell.selectBtn.titleLabel.text address:_addressEditCell.addressTf.text];
        }
        
        [request completion:^(id result, NSString *message, id extension, BOOL succ) {
            if (succ)
            {
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                [SVProgressHUD showErrorWithStatus:message];
            }
        }];
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:@"请输入完整信息"];
    }
}


#pragma mark tableViewDelegate,DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.requestType == RequestTypeAddAddress ? 1 : 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section)
    {
        case 0:
        {
            return 1;
        }
            break;
        case 1:
        {
            return 1;
        }
            break;
        default:
            break;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1)
    {
        return 40;
    }
    else
    {
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1)
    {
        UIView *view = [UIView new];
        view.backgroundColor = KwBgColor;
        return view;
    }
    else
    {
        return nil;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *addressEditCell_ID = @"AddressEditCell";
    static NSString *deleteCell_ID = @"DeleteCell";
    
    if (indexPath.section == 0)
    {
        
        _addressEditCell = [tableView dequeueReusableCellWithIdentifier:addressEditCell_ID];
        if (!_addressEditCell)
        {
            _addressEditCell = [[AddressEditCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:addressEditCell_ID];
        }
        if (self.requestType == RequestTypeEditAddress)
        {
            _addressEditCell.model = _model;
        }
        _addressEditCell.selectionStyle = UITableViewCellSelectionStyleNone;
        __weak typeof(_addressEditCell) weakCell = _addressEditCell;
        _addressEditCell.block = ^(NSString *areaStr){
            [weakCell.selectBtn setTitle:areaStr forState:UIControlStateNormal];
        };
        return _addressEditCell;
    }
    else
    {
        UITableViewCell *cell;
        cell = [tableView dequeueReusableCellWithIdentifier:deleteCell_ID];
        if (!cell)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:deleteCell_ID];
            cell.backgroundColor = [UIColor whiteColor];
            UILabel *deleteLab = [UILabel new];
            deleteLab.text = @"删除地址";
            deleteLab.textColor = KwBlueColor;
            deleteLab.font = KwFont(15 * screenW_6);
            [cell.contentView addSubview:deleteLab];
            [deleteLab mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(cell.mas_centerX);
                make.height.equalTo(@(15 *screenW_6));
                make.top.equalTo(@(15 *screenW_6));
                make.bottom.equalTo(@(-15 * screenW_6));
            }];
            
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1)
    {
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"确定删除？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        //删除操作
        if (self.requestType == RequestTypeAddAddress)
        {
            //添加操作直接返回
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            //编辑操作,请求删除
            NWAddressRequest *request = [[NWAddressRequest alloc] init];
            [request startRequestDeleteAddressWithAId:_model.id];
            [request completion:^(id result, NSString *message, id extension, BOOL succ) {
                [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
        }

    }
}

@end
